﻿/**
* jpage for  jQuery分页插件
* 功能：指定页数内静态分页，超过指定页数后ajax请求下一组静态分页
* 修改：LiuY 2011-10-21 
* 描述：展现方式改成table ，并改正数据不足1页时，刷新报错，以及页码显示不正常
*/
jQuery.fn.jpage = function(config) {
    init("#" + this.attr("id"), config);

    /**
    * 初始化，主程序
    * @param t 容器的ID，带#号
    * @param config 插件配置
    */
    function init(t, config) {

        var op = {
            themeName: 'rotundity', //主题名称
            openCookies: false, //是否读取cookies
            showMode: 'full', //显示模式
            tableId: 'GridView', //列表id
            tableClass: 'tabbar', //列表样式     
            dataBefore: '<table>',
            dataHead: '',
            dataHeadEnd: '</thead>',
            dataAfter: '</table>', //循环后内容
            proxyUrl: Common.GetServicePath() + "WebService/JqueryService.asmx/GetMyDatas", //代理页地址	
            groupSize: 10, //分组大小
            perPage: 10, //每页记录数
            barPosition: 'bottom', //分页条位置
            openkey: '1', //是否开启键盘控制上下页             
            ajaxParam: {}
        };
        var opajax = {
            hidetextlength: '100',
            filedswidth: '',
            checktype: '',
            renderfield: '',
            beforextends: '',
            afterextends: '',
            checkclickfn: '',
            wherevalue: '',
            classs: '',
            rowclickfn: '',
            rowshowattr: '',
            showsort: '1',
            extendbreak: '0',
            indexfield: 'id'
        };
        $.extend(op, config);
        $.extend(opajax, config.ajaxParam);
        op.ajaxParam = opajax;
        //公有变量
        if (!t)
            return;
        var _id = $(t).attr("id");
        var dataStore = op.dataStore; 																		//数据
        var openCookies = op.openCookies != null ? op.openCookies : true;

        if (!openCookies) {
            Common.RemoveCookie("datalistperPage");
        }
        var configPage = op.perPage > 0 ? op.perPage : 10;
        var _dPage = Common.GetCookie("datalistperPage");

        if ((isNaN(_dPage) || _dPage == "") || !op.openCookies) {

            _dPage = configPage;

        }

        var perPage = _dPage; //每页显示记录数


        var totalRecord = op.totalRecord; 																	//总记录数
        if (totalRecord == undefined)
            totalRecord = 0;
        else {
            totalRecord = op.totalRecord > 0 ? op.totalRecord : 0;
            if (totalRecord == 0) {
                $(t).css("text-align", "center");
                $(t).css("line-height", "50px");
                $(t).html("没有检索到任何记录！");
                return;
            }
        }
        var proxyUrl = op.proxyUrl; 								//数据代理地址
        var groupSize = op.groupSize; 	//组大小
        var barPosition = op.barPosition; //工具条位置
        var ajaxParam = op.ajaxParam; 																		//ajax的请求参数
        var showMode = op.showMode; 				//显示模式
        var allowChangePerPage = true; 	//是否允许切换每页显示数
        var themeName = op.themeName; 		//主题名称
        var dataBefore = '<table id="' + op.tableId + '" class="' + op.tableClass + '" style="width:100%"><thead>';
        var dataHead = op.dataHead;
        var dataHeadEnd = op.dataHeadEnd;
        var dataAfter = op.dataAfter;
        var callBack = op.callBack == null ? function() { } : op.callBack;

        //私有变量
        var totalPage = Math.ceil(totalRecord / perPage);
        var _dcpage = Common.GetCookie(_id + "_datalistcurrentPage");
        if (isNaN(_dcpage) || _dcpage == "") {
            _dcpage = 1;
        }
        //总页数
        var currentPage = !openCookies || _dcpage; //当前页码
        var startRecord; 																						//每页起始记录，相对于当前组
        var endRecord;  																							//每页结束记录，相对于当前组
        var gpStartPage; 																						//组开始页
        var gpEndPage; 																							//组结束页
        var gpStartRecord = 1; 																					//组开始记录
        var gpEndRecord = perPage * groupSize;

        //数据容器
        var container = '<div class="' + themeName + '_pgContainer"></div>';

        //添加工具条
        var toolbar = '<div sizset="0" class="l-panel-bar"><div class="l-panel-bbar-inner" sizset="0">';
        toolbar += '<div class="l-bar-group l-bar-selectpagesize" sizset="0">每页显示<select class="' + themeName + '_pgPerPage" name="rp" >';
        toolbar += '<option value="5">5</option>';
        toolbar += '<option value="10">10</option>';
        toolbar += '<option value="15">15</option>';
        toolbar += '<option value="20">20</option>';
        toolbar += '<option value="25">25</option>';
        toolbar += '<option value="40">40</option>';
        toolbar += '<option value="100">100</option>';
        toolbar += '<option value="500">500</option>';
        toolbar += '</select>条&nbsp;</div>';
        toolbar += '<div class="l-bar-separator"></div>';
        toolbar += '<div class="l-bar-group" sizset="1"><div class="l-bar-button l-bar-btnfirst" title="首页" sizset="1"><span class="l-disabled"></span></div>';
        toolbar += '<div class="l-bar-button l-bar-btnprev" title="上页" sizset="2"><span class="l-disabled"></span></div></div>';

        toolbar += '<div class="l-bar-separator"></div><div class="l-bar-group" sizset="3"><span class="pcontrol" sizset="4">';
        toolbar += '第<input class="' + themeName + '_pgCurrentPage" type="text" value="' + currentPage + '" size="4"> 页 / 共 <span class="' + themeName + '_pgTotalPage">' + totalPage + '</span> 页</span></div>';
        toolbar += '<div class="l-bar-separator"></div><div class="l-bar-group" sizset="6"><div class="l-bar-button l-bar-btnnext" title="下页" sizset="5"><span></span></div>';

        toolbar += '<div class="l-bar-button l-bar-btnlast" title="尾页" sizset="6"><span></span></div></div>';
        toolbar += '<div class="l-bar-separator"></div>';


        if (groupSize) {
            toolbar += '<div class="l-bar-group" sizset="7">';
            toolbar += '<div class="l-bar-button l-bar-btnload" title="刷新" sizset="7"><span></span></div></div>';
        }
        toolbar += '<div class="l-bar-separator"></div>';
        toolbar += '<div class="l-bar-groupl-bar-message right" sizset="0">';
        if (showMode == 'full' && allowChangePerPage) {
            toolbar += '<span class="l-bar-text">显示第&nbsp;<span class="' + themeName + '_pgStartRecord">' + startRecord + '</span>&nbsp;条&nbsp;到 &nbsp;第&nbsp;<span class="' + themeName + '_pgEndRecord">' + endRecord + '</span>&nbsp;条，共 <span class="totalRecord">' + totalRecord + '</span> 条 。</div>';
            toolbar += '';
        }
        toolbar += '<div class="l-clear"></div></div></div>';

        switch (barPosition) {
            case 'top':
                $(t).html(toolbar + container);
                break;
            case 'bottom':
                $(t).html(container + toolbar);
                break;
            case 'no':
                $(t).html(container);
                break;
            default:
                $(t).html(toolbar + container + toolbar);
        }

        var btnRefresh = $(t + " .l-bar-btnload"); 														//刷新按钮
        var btnNext = $(t + " .l-bar-btnnext"); 																//下一页按钮
        var btnPrev = $(t + " .l-bar-btnprev"); 																//上一页按钮
        var btnFirst = $(t + " .l-bar-btnfirst"); 															//首页按钮
        var btnLast = $(t + " .l-bar-btnlast"); 																//末页按钮
        var btnGo = $(t + " .l-bar-btnnext," + t + " .l-bar-btnlast");
        var btnBack = $(t + " .l-bar-btnprev," + t + " .l-bar-btnfirst");
        var btn = $(t + " .l-bar-btnfirst," + t + " .l-bar-btnprev," + t + " .l-bar-btnnext," + t + " .l-bar-btnlast");
        var mask;

        var valCurrentPage = $(t + " ." + themeName + "_pgCurrentPage");
        var valStartRecord = $(t + " ." + themeName + "_pgStartRecord");
        var valEndRecord = $(t + " ." + themeName + "_pgEndRecord");
        var valContainer = $(t + " ." + themeName + "_pgContainer");
        var valPerPage = $(t + " ." + themeName + "_pgPerPage");
        $(valPerPage).val(op.perPage);
        var valTotalPage = $(t + " ." + themeName + "_pgTotalPage");

        $(t + " ." + themeName + "_pgPerPage").attr("value", perPage);
        getGroupStartEnd();
        getStartEnd();

        if (dataStore == null || perPage != configPage)
            getRemoteData();
        else {
            getStartEnd();
            loadData();
            refresh();
        }

        //刷新按钮监听
        btnRefresh.bind("mousedown", pressHandler).bind("mouseup", unpressHandler).bind("mouseout", unpressHandler);

        //刷新工具栏
        refresh();

        if (op.openkey == "1") {
            $("body").parent().children().keydown(function() {
                var asciicode = event.keyCode;
                if (asciicode == 39 || asciicode == 34) {
                    nextpage();
                }
                else if (asciicode == 37 || asciicode == 33) {
                    $(btnPrev).click();
                }
            });
        }

        //下一页
        function nextpage() {
            if (currentPage < totalPage) {
                if (!dataStore || currentPage == gpEndPage - 1) {
                    currentPage = Number(currentPage);
                    currentPage += 1;
                    getGroupStartEnd();
                    getStartEnd();
                    getRemoteData();
                } else {
                    currentPage += 1;
                    getStartEnd();
                    loadData();
                    refresh();
                }
            }
        }

        //上一页
        function prevpage() {
            if (currentPage > 1) {
                if (!dataStore || currentPage == gpStartPage) {
                    currentPage = Number(currentPage);
                    currentPage -= 1;
                    getGroupStartEnd();
                    getStartEnd();
                    getRemoteData();
                } else {
                    currentPage = Number(currentPage);
                    currentPage -= 1;
                    getStartEnd();
                    loadData();
                    refresh();
                }
            }
        }

        //按钮监听
        btnNext.click(
				function() {
				    clearSelect();
				    nextpage();
				}
			);
        btnPrev.click(
				function() {
				    clearSelect();
				    prevpage();
				}
			);
        btnFirst.click(
				function() {
				    clearSelect();
				    if (!dataStore || currentPage > 1) {
				        if (gpStartPage > 1) {
				            currentPage = Number(currentPage);
				            currentPage = 1;
				            getGroupStartEnd();
				            getStartEnd();
				            getRemoteData();
				        } else {
				            currentPage = Number(currentPage);
				            currentPage = 1;
				            getStartEnd();
				            loadData();
				            refresh();
				        }
				    }
				}
			);
        btnLast.click(
				function() {
				    clearSelect();
				    if (!dataStore || currentPage < totalPage) {
				        if (gpEndPage > 0 && gpEndPage < totalPage) {
				            currentPage = totalPage;
				            currentPage = Number(currentPage);
				            getGroupStartEnd();
				            getStartEnd();
				            getRemoteData();
				        } else {
				            currentPage = totalPage;
				            currentPage = Number(currentPage);
				            getStartEnd();
				            loadData();
				            refresh();
				        }
				    }
				}
			);
        btnRefresh.click(
				function() {
				    clearSelect();
				    getGroupStartEnd();
				    getStartEnd();
				    getRemoteData();
				}
			);

        //页码输入框监听
        valCurrentPage.keydown(
				function(event) {
				    var targetPage = parseInt($(this).val());
				    if (event.keyCode == 13 && targetPage >= 1 && targetPage <= totalPage) {
				        if (!dataStore || gpStartPage > targetPage || (gpEndPage > 0 && gpEndPage < targetPage)) {
				            currentPage = targetPage;
				            currentPage = Number(currentPage);
				            getGroupStartEnd();
				            getStartEnd();
				            getRemoteData();
				        } else {
				            currentPage = targetPage;
				            currentPage = Number(currentPage);
				            getStartEnd();
				            loadData();
				            refresh();
				        }
				    }
				    event.keyCode = 0;
				}
			);

        valPerPage.change(
				function() {
				    valPerPage.val($(this).val());
				    perPage = $(this).val();

				    currentPage = 1;
				    totalPage = Math.ceil(totalRecord / perPage);
				    if (groupSize) {
				        getGroupStartEnd();
				        getStartEnd();
				        getRemoteData();
				    } else {
				        getStartEnd();
				        loadData();
				        refresh();
				    }
				}
			);

        /*********************************init私有函数***************************************************/
        /**
        * 置为正在检索状态
        */
        function startLoad() {
            $(t).addClass(themeName + "_container");
            mask = document.createElement('div');
            $(mask).addClass(themeName + "_mask");
            $(mask).css("height", $(t).height());
            $(t).append(mask);
            $(t + " .l-bar-btnload").addClass(themeName + "_pgLoad");
            $(t + " ." + themeName + "_pgSearchInfo").html("正在检索中，请稍后...");
        }

        /**
        * 置为结束检索状态
        */
        function overLoad() {
            $(t + " .l-bar-btnload").removeClass(themeName + "_pgLoad");
            $(t + " ." + themeName + "_pgSearchInfo").html('检索到&nbsp;' + totalRecord + '&nbsp;条记录，显示第&nbsp;<span class="' + themeName + '_pgStartRecord">' + (startRecord + gpStartRecord - 1) + '</span>&nbsp;条&nbsp;-&nbsp;第&nbsp;<span class="' + themeName + '_pgEndRecord">' + (endRecord + gpStartRecord - 1) + '</span>&nbsp;条记录');
            $(mask).remove();
            $(t).removeClass(themeName + "_container");
            valStartRecord = $(t + " ." + themeName + "_pgStartRecord");
            valEndRecord = $(t + " ." + themeName + "_pgEndRecord");
        }

        /**
        * 获得远程数据
        */
        function getRemoteData() {
            startLoad();
            ajaxParam = Common.JsonAdd(ajaxParam, "startrecord", "'" + gpStartRecord + "'");
            ajaxParam = Common.JsonAdd(ajaxParam, "endrecord", "'" + gpEndRecord + "'");
            ajaxParam = Common.JsonAdd(ajaxParam, "perpage", "'" + perPage + "'");
            $.ajax(
					{
					    type: "POST",
					    contentType: "application/json",
					    url: proxyUrl,
					    cache: false,
					    data: Common.Json2String(ajaxParam),
					    dataType: "json",
					    timeout: 30000,
					    success: function(msg) {

					        eval(msg.d);
					        if (totalRecord == 0)
					            $('.' + themeName + '_pgToolbar').remove();
					        $(".totalRecord").html(totalRecord);
					        getStartEnd();
					        loadData();
					        refresh();
					        overLoad();
					    },
					    error: function(XMLHttpRequest, textStatus, errorThrown) {
					        alert("请求失败或超时，请稍后再试！");
					        overLoad();
					        return;
					    }
					}
				);
        }

        /**
        * 获得当前页开始结束记录
        */
        function getStartEnd() {
            if (groupSize) {
                startRecord = (currentPage - 1) * perPage + 1 - gpStartRecord + 1;
                endRecord = Math.min(currentPage * perPage, totalRecord) - gpStartRecord + 1;
            } else {
                startRecord = (currentPage - 1) * perPage + 1;
                endRecord = Math.min(currentPage * perPage, totalRecord);
            }
        }

        /**
        * 获得当前组开始结束页码
        */
        function getGroupStartEnd() {
            if (groupSize == null)
                return;
            var groupId = groupSize > 0 ? Math.ceil(currentPage / groupSize) : 0;
            gpStartPage = (groupId - 1) * groupSize + 1;
            gpEndPage = Math.min(groupId * groupSize, totalPage);
            gpStartRecord = (gpStartPage - 1) * perPage + 1;
            if (totalRecord > 0) {
                gpEndRecord = Math.min(gpEndPage * perPage, totalRecord);
                gpEndPage += 1;
            }
        }

        /**
        * 刷新数据容器
        */
        function loadData() {
            if (dataStore == null || dataStore.length == 0) {
                valContainer.css("text-align", "center");
                valContainer.css("line-height", "50px");
                valContainer.html("没有检索到任何记录！");
                return;
            }

            var view = "";
            for (var i = startRecord - 1; i <= endRecord - 1; i++) {
                if (dataStore[i]) {
                    view += dataStore[i].replace("{id}", gpStartRecord + i);
                }
            }
            valContainer.html(dataBefore + dataHead + dataHeadEnd + view + dataAfter);


            //翻页回调函数
            callBack();
            getGroupStartEnd();
        }

        //清空选择项
        function clearSelect() {
            $("#" + _id).data("indexvalue", "");
        }

        /**
        * 刷新工具栏状态
        */
        function refresh() {
            if (openCookies) {
                //当前页码写入cookie
                Common.SetCookie(_id + '_datalistcurrentPage', currentPage);
                Common.SetCookie('datalistperPage', perPage);
            }
            currentPage = Number(currentPage);
            valCurrentPage.val(currentPage);
            valStartRecord.html(startRecord + gpStartRecord - 1);
            valEndRecord.html(endRecord + gpStartRecord - 1);
            totalPage = totalRecord / perPage;
            if (totalRecord % perPage > 0) {
                totalPage = Math.floor(totalRecord / perPage) + 1;
            }
            valTotalPage.html(totalPage);

            btn.unbind("mousedown", pressHandler);
            btn.bind("mouseup", unpressHandler);
            btn.bind("mouseout", unpressHandler);
            if (currentPage == 1 && currentPage != totalPage) {
                enabled();
                btnGo.bind("mousedown", pressHandler);

                $(btnPrev).find("span").addClass("l-disabled");
                $(btnFirst).find("span").addClass("l-disabled");

            } else if (currentPage != 1 && currentPage == totalPage) {
                enabled();
                btnBack.bind("mousedown", pressHandler);
                $(btnNext).find("span").addClass("l-disabled");
                $(btnLast).find("span").addClass("l-disabled");
            } else if (currentPage == 1 && currentPage == totalPage) {
                disabled();
            } else {
                enabled();
                btnBack.bind("mousedown", pressHandler);
                btnGo.bind("mousedown", pressHandler);
                btnNext.addClass("l-bar-btnnext");
                btnPrev.addClass("l-bar-btnprev");
                btnFirst.addClass("l-bar-btnfirst");
                btnLast.addClass("l-bar-btnlast");
            }
        }

        /**
        * 移除按钮disabled状态样式
        */
        function enabled() {
            $(btnNext).find("span").removeClass("l-disabled");
            $(btnPrev).find("span").removeClass("l-disabled");
            $(btnFirst).find("span").removeClass("l-disabled");
            $(btnLast).find("span").removeClass("l-disabled");
        }

        /**
        * 添加按钮disabled状态样式
        */
        function disabled() {
            $(btnNext).find("span").addClass("l-disabled");
            $(btnPrev).find("span").addClass("l-disabled");
            $(btnFirst).find("span").addClass("l-disabled");
            $(btnLast).find("span").addClass("l-disabled");
        }

        /**
        * 添加按钮按下状态样式
        */
        function pressHandler() {
            $(this).addClass(themeName + "_pgPress");
        }

        /**
        * 移除按钮按下状态样式
        */
        function unpressHandler() {
            $(this).removeClass(themeName + "_pgPress");
        }
    }
};